const mongoose = require('mongoose')
const Content = require('../../model/content')
const Reply = require('../../model/reply')
const Normal = require('../../model/normal')
const delReply = require('./toreply')


module.exports = async (req, res) => {
    const { id, flag } = req.params
    var author
    if (flag == 1) {
        try {
            const a = await Content.findOne({ _id: id }).select('child -_id author')
            const c = await Content.deleteOne({ _id: id })
            author = a.author
            a.child.forEach(element => {
                delReply(element)
            });
            var num1 = await Content.find({author}).count()
            var num2 = await Reply.find({
                $or: [
                    { author }, { reply: author }
                ]
            }).count()
            var num3 = await  message.find({author}).count()
            if (num1 == 0 && num2 == 0 && num3 == 0) {
                const d = await Normal.deleteOne({ _id: author, type: 'user' })
            }
        } catch (err) {
            console.log(err);
            return res.send({
                data: null,
                meta: {
                    status: 400,
                    msg: '删除失败'
                }
            })
        }

    } else {
        try {
            delReply(id)
        } catch {
            return res.send({
                data: null,
                meta: {
                    status: 400,
                    msg: '删除失败'
                }
            })
        }
    }

    res.send({
        data: null,
        meta: {
            status: 204,
            msg: '删除成功'
        }
    })
}